<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>小说转漫画 - AI创作工具</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Microsoft YaHei', sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }
        
        .container {
            max-width: 1200px;
            margin: 0 auto;
            background: white;
            border-radius: 20px;
            box-shadow: 0 20px 40px rgba(0,0,0,0.1);
            overflow: hidden;
        }
        
        .header {
            background: linear-gradient(135deg, #ff6b6b, #ffa500);
            color: white;
            padding: 30px;
            text-align: center;
        }
        
        .header h1 {
            font-size: 2.5em;
            margin-bottom: 10px;
        }
        
        .header p {
            font-size: 1.2em;
            opacity: 0.9;
        }
        
        .main-content {
            padding: 40px;
        }
        
        .form-section {
            margin-bottom: 40px;
        }
        
        .form-group {
            margin-bottom: 25px;
        }
        
        label {
            display: block;
            margin-bottom: 8px;
            font-weight: bold;
            color: #333;
        }
        
        textarea, select, input {
            width: 100%;
            padding: 15px;
            border: 2px solid #e1e5e9;
            border-radius: 10px;
            font-size: 16px;
            transition: border-color 0.3s;
        }
        
        textarea {
            min-height: 200px;
            resize: vertical;
        }
        
        textarea:focus, select:focus, input:focus {
            outline: none;
            border-color: #667eea;
        }
        
        .style-options {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
            gap: 15px;
            margin-top: 10px;
        }
        
        .style-option {
            padding: 15px;
            border: 2px solid #e1e5e9;
            border-radius: 10px;
            text-align: center;
            cursor: pointer;
            transition: all 0.3s;
        }
        
        .style-option:hover {
            border-color: #667eea;
            background: #f8f9ff;
        }
        
        .style-option.selected {
            border-color: #667eea;
            background: #667eea;
            color: white;
        }
        
        .btn {
            background: linear-gradient(135deg, #667eea, #764ba2);
            color: white;
            border: none;
            padding: 15px 30px;
            border-radius: 10px;
            font-size: 16px;
            cursor: pointer;
            transition: transform 0.3s;
            margin-right: 10px;
        }
        
        .btn:hover {
            transform: translateY(-2px);
        }
        
        .btn:disabled {
            opacity: 0.6;
            cursor: not-allowed;
            transform: none;
        }
        
        .loading {
            display: none;
            text-align: center;
            padding: 20px;
        }
        
        .spinner {
            border: 4px solid #f3f3f3;
            border-top: 4px solid #667eea;
            border-radius: 50%;
            width: 40px;
            height: 40px;
            animation: spin 1s linear infinite;
            margin: 0 auto 20px;
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        
        .results {
            margin-top: 40px;
            display: none;
        }
        
        .comic-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
            gap: 20px;
            margin-top: 20px;
        }
        
        .comic-panel {
            border: 2px solid #e1e5e9;
            border-radius: 15px;
            overflow: hidden;
            background: white;
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
        }
        
        .comic-panel img {
            width: 100%;
            height: 300px;
            object-fit: cover;
        }
        
        .panel-info {
            padding: 15px;
        }
        
        .panel-info h4 {
            color: #333;
            margin-bottom: 8px;
        }
        
        .panel-info p {
            color: #666;
            font-size: 14px;
        }
        
        .error {
            background: #fee;
            color: #c33;
            padding: 15px;
            border-radius: 10px;
            margin: 20px 0;
        }
        
        .success {
            background: #efe;
            color: #3c3;
            padding: 15px;
            border-radius: 10px;
            margin: 20px 0;
        }
        
        .panel-selection {
            margin: 20px 0;
            padding: 20px;
            background: #f8f9ff;
            border-radius: 10px;
            border: 2px solid #e1e5e9;
        }
        
        .panel-checkbox {
            display: block;
            margin: 10px 0;
            padding: 10px;
            background: white;
            border-radius: 8px;
            cursor: pointer;
            transition: background-color 0.3s;
        }
        
        .panel-checkbox:hover {
            background: #f0f0f0;
        }
        
        .panel-checkbox input[type="checkbox"] {
            margin-right: 10px;
            transform: scale(1.2);
        }
        
        .panel-checkbox span {
            font-size: 14px;
            line-height: 1.4;
        }
        
        .download-btn {
            background: linear-gradient(135deg, #28a745, #20c997);
            color: white;
            border: none;
            padding: 8px 16px;
            border-radius: 5px;
            font-size: 12px;
            cursor: pointer;
            margin: 5px;
            transition: transform 0.3s;
        }
        
        .download-btn:hover {
            transform: translateY(-1px);
        }
        
        .image-container {
            position: relative;
            display: inline-block;
        }
        
        .image-overlay {
            position: absolute;
            top: 10px;
            right: 10px;
            background: rgba(0,0,0,0.7);
            color: white;
            padding: 5px 10px;
            border-radius: 5px;
            font-size: 12px;
        }
        
        .image-status {
            margin-top: 10px;
            padding: 8px;
            border-radius: 5px;
            font-size: 12px;
        }
        
        .status-success {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        
        .status-error {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        
        .status-info {
            background: #d1ecf1;
            color: #0c5460;
            border: 1px solid #bee5eb;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>🎨 小说转漫画</h1>
            <p>AI智能创作，让文字变成生动的漫画</p>
        </div>
        
        <div class="main-content">
            <form id="comicForm">
                <div class="form-section">
                    <div class="form-group">
                        <label for="novelText">📖 输入小说文本</label>
                        <textarea id="novelText" placeholder="请粘贴您的小说文本，系统将自动分析情节并生成漫画分镜..."></textarea>
                    </div>
                    
                    <div class="form-group">
                        <label>🎨 选择画风</label>
                        <div class="style-options">
                            <div class="style-option selected" data-style="日系">日系漫画</div>
                            <div class="style-option" data-style="国潮">国潮风格</div>
                            <div class="style-option" data-style="Q版">Q版卡通</div>
                            <div class="style-option" data-style="写实">写实风格</div>
                            <div class="style-option" data-style="古风">古风漫画</div>
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <label for="targetScene">🎯 目标场景</label>
                        <select id="targetScene">
                            <option value="通用">通用场景</option>
                            <option value="教育">教育场景</option>
                            <option value="儿童">儿童读物</option>
                            <option value="二次创作">二次创作</option>
                            <option value="商业">商业用途</option>
                        </select>
                    </div>
                    
                    <div class="form-group">
                        <label for="panelCount">🎬 分镜数量 (1-12张)</label>
                        <select id="panelCount">
                            <option value="1">1格漫画</option>
                            <option value="2">2格漫画</option>
                            <option value="3">3格漫画</option>
                            <option value="4" selected>4格漫画</option>
                            <option value="5">5格漫画</option>
                            <option value="6">6格漫画</option>
                            <option value="7">7格漫画</option>
                            <option value="8">8格漫画</option>
                            <option value="9">9格漫画</option>
                            <option value="10">10格漫画</option>
                            <option value="11">11格漫画</option>
                            <option value="12">12格漫画</option>
                        </select>
                    </div>
                    
                    <button type="submit" class="btn" id="analyzeBtn">🔍 分析文本</button>
                    <button type="button" class="btn" id="generateBtn" disabled>🎨 生成漫画</button>
                </div>
            </form>
            
            <div class="loading" id="loading">
                <div class="spinner"></div>
                <p>AI正在分析文本，请稍候...</p>
            </div>
            
            <div class="results" id="results">
                <h3>📊 分析结果</h3>
                <div id="analysisResult"></div>
                
                <h3>🎨 生成的漫画</h3>
                <div class="comic-grid" id="comicGrid"></div>
            </div>
        </div>
    </div>

    <script>
        let selectedStyle = '日系';
        let analysisData = null;
        
        // 画风选择
        document.querySelectorAll('.style-option').forEach(option => {
            option.addEventListener('click', function() {
                document.querySelectorAll('.style-option').forEach(opt => opt.classList.remove('selected'));
                this.classList.add('selected');
                selectedStyle = this.dataset.style;
            });
        });
        
        // 表单提交
        document.getElementById('comicForm').addEventListener('submit', async function(e) {
            e.preventDefault();
            
            const text = document.getElementById('novelText').value.trim();
            const targetScene = document.getElementById('targetScene').value;
            
            if (!text) {
                alert('请输入小说文本');
                return;
            }
            
            await analyzeText(text, selectedStyle, targetScene);
        });
        
        // 生成漫画按钮
        document.getElementById('generateBtn').addEventListener('click', async function() {
            if (!analysisData) {
                alert('请先分析文本');
                return;
            }
            
            await generateComic();
        });
        
        // 分析文本
        async function analyzeText(text, style, targetScene) {
            showLoading(true);
            hideResults();
            
            // 获取分镜数量
            const panelCount = document.getElementById('panelCount').value;
            
            try {
                const response = await fetch('/api/analyze', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        text: text,
                        style: style,
                        target_scene: targetScene,
                        panel_count: parseInt(panelCount)
                    })
                });
                
                const result = await response.json();
                
                if (result.success) {
                    analysisData = JSON.parse(result.analysis);
                    displayAnalysis(analysisData);
                    document.getElementById('generateBtn').disabled = false;
                    showSuccess('文本分析完成！可以开始生成漫画了。');
                } else {
                    showError('分析失败：' + result.error);
                }
            } catch (error) {
                showError('网络错误：' + error.message);
            } finally {
                showLoading(false);
            }
        }
        
        // 生成漫画
        async function generateComic() {
            showLoading(true);
            
            // 获取选中的分镜
            const selectedPanels = [];
            document.querySelectorAll('.panel-checkbox input:checked').forEach(checkbox => {
                selectedPanels.push(parseInt(checkbox.value));
            });
            
            if (selectedPanels.length === 0) {
                showError('请至少选择一个分镜');
                showLoading(false);
                return;
            }
            
            try {
                const response = await fetch('/api/generate', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        panels: analysisData.panels,
                        style: selectedStyle,
                        characters: analysisData.characters,
                        selected_panels: selectedPanels
                    })
                });
                
                const result = await response.json();
                
                if (result.success) {
                    displayComic(result.panels);
                    showResults();
                    showSuccess(`漫画生成完成！已生成 ${result.panels.length} 个分镜。`);
                } else {
                    showError('生成失败：' + result.error);
                }
            } catch (error) {
                showError('网络错误：' + error.message);
            } finally {
                showLoading(false);
            }
        }
        
        // 显示分析结果
        function displayAnalysis(data) {
            const analysisDiv = document.getElementById('analysisResult');
            let html = '<div class="success">✅ 文本分析完成</div>';
            
            if (data.characters && data.characters.length > 0) {
                html += '<h4>👥 识别的人物：</h4><ul>';
                data.characters.forEach(char => {
                    html += `<li><strong>${char.name}</strong>: ${char.description}</li>`;
                });
                html += '</ul>';
            }
            
            if (data.panels && data.panels.length > 0) {
                html += `<h4>🎬 分镜规划 (${data.panels.length}格)：</h4>`;
                html += '<div class="panel-selection">';
                html += '<p>请选择要生成的分镜（可多选）：</p>';
                data.panels.forEach(panel => {
                    html += `
                        <label class="panel-checkbox">
                            <input type="checkbox" value="${panel.panel_id}" checked>
                            <span><strong>分镜 ${panel.panel_id}</strong>: ${panel.scene} - ${panel.action}</span>
                        </label>
                    `;
                });
                html += '</div>';
            }
            
            analysisDiv.innerHTML = html;
        }
        
        // 显示漫画
        function displayComic(panels) {
            const grid = document.getElementById('comicGrid');
            let html = '';
            
            panels.forEach(panel => {
                // 检查是否生成成功
                if (panel.success === false) {
                    // 生成失败，直接显示失败信息
                    html += `
                        <div class="comic-panel">
                            <div class="panel-info">
                                <h4>分镜 ${panel.panel_id}</h4>
                                <p><strong>场景:</strong> ${panel.scene || 'N/A'}</p>
                                <p><strong>动作:</strong> ${panel.action || 'N/A'}</p>
                                <div class="image-status status-error">
                                    <strong>❌ 生成失败:</strong><br>
                                    ${panel.error}
                                </div>
                                ${panel.visual_prompt ? `
                                    <div style="margin-top: 10px; padding: 10px; background: #fff3cd; border-radius: 5px; font-size: 12px;">
                                        <strong>视觉提示词:</strong><br>
                                        ${panel.visual_prompt}
                                    </div>
                                ` : ''}
                            </div>
                        </div>
                    `;
                } else if (panel.image_url || panel.image_data || panel.local_url) {
                    // 生成成功，显示图片
                    const imageSrc = panel.local_url || panel.image_url || panel.image_data;
                    const downloadButtons = getDownloadButtons(panel);
                    const statusInfo = getStatusInfo(panel);
                    
                    html += `
                        <div class="comic-panel">
                            <div class="image-container">
                                <img src="${imageSrc}" alt="漫画分镜" style="width: 100%; height: 300px; object-fit: cover; border-radius: 10px 10px 0 0;">
                                <div class="image-overlay">分镜 ${panel.panel_id}</div>
                            </div>
                            <div class="panel-info">
                                <h4>分镜 ${panel.panel_id}</h4>
                                <p><strong>场景:</strong> ${panel.scene}</p>
                                <p><strong>动作:</strong> ${panel.action}</p>
                                ${statusInfo}
                                ${downloadButtons}
                            </div>
                        </div>
                    `;
                } else {
                    // 其他错误情况
                    html += `
                        <div class="comic-panel">
                            <div class="panel-info">
                                <h4>分镜 ${panel.panel_id}</h4>
                                <p class="error">生成失败: ${panel.error || '未知错误'}</p>
                            </div>
                        </div>
                    `;
                }
            });
            
            grid.innerHTML = html;
        }
        
        // 获取下载按钮
        function getDownloadButtons(panel) {
            let buttons = '';
            
            if (panel.filename) {
                buttons += `<button class="download-btn" onclick="downloadImage('${panel.filename}')">📥 下载图片</button>`;
            }
            
            if (panel.image_url) {
                buttons += `<button class="download-btn" onclick="downloadFromUrl('${panel.image_url}', 'panel_${panel.panel_id}')">📥 下载原图</button>`;
            }
            
            return buttons ? `<div style="margin-top: 10px;">${buttons}</div>` : '';
        }
        
        // 获取状态信息
        function getStatusInfo(panel) {
            let status = '';
            
            if (panel.download_success) {
                status += `<div class="image-status status-success">✅ 图片已下载到本地: ${panel.filename}</div>`;
            } else if (panel.download_error) {
                status += `<div class="image-status status-error">❌ 下载失败: ${panel.download_error}</div>`;
            }
            
            if (panel.image_error) {
                status += `<div class="image-status status-error">⚠️ 图片生成问题: ${panel.image_error}</div>`;
            }
            
            return status;
        }
        
        // 下载图片
        function downloadImage(filename) {
            window.open(`/api/download/${filename}`, '_blank');
        }
        
        // 从URL下载图片
        function downloadFromUrl(url, filename) {
            const link = document.createElement('a');
            link.href = url;
            link.download = `${filename}.png`;
            link.target = '_blank';
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        }
        
        // 工具函数
        function showLoading(show) {
            document.getElementById('loading').style.display = show ? 'block' : 'none';
        }
        
        function showResults() {
            document.getElementById('results').style.display = 'block';
        }
        
        function hideResults() {
            document.getElementById('results').style.display = 'none';
        }
        
        function showError(message) {
            const errorDiv = document.createElement('div');
            errorDiv.className = 'error';
            errorDiv.textContent = message;
            document.querySelector('.main-content').insertBefore(errorDiv, document.getElementById('results'));
            setTimeout(() => errorDiv.remove(), 5000);
        }
        
        function showSuccess(message) {
            const successDiv = document.createElement('div');
            successDiv.className = 'success';
            successDiv.textContent = message;
            document.querySelector('.main-content').insertBefore(successDiv, document.getElementById('results'));
            setTimeout(() => successDiv.remove(), 3000);
        }
    </script>
</body>
</html>
